package com.vincce.sport.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.entity.Page;
import com.vincce.sport.entity.SysResource;
import com.vincce.sport.entity.SysResourceRole;
import com.vincce.sport.entity.SysRole;
import com.vincce.sport.mapper.SysResourceMapper;
import com.vincce.sport.mapper.SysRoleMapper;

@Controller
@RequestMapping("/sysRole")
public class SysRoleController extends BaseController{

	@Resource
	private SysRoleMapper sysRoleMapper;
	
	@Resource
	private SysResourceMapper sysResourceMapper;
	
    @RequestMapping("/list")
    public String sysRoleList(Model model, SysRole sysRole, Page<SysRole> page) throws IOException{
        Map<String, Object> filter = new HashMap<String, Object>();
        if(sysRole.getRoleName() != null && !sysRole.getRoleName().equals("")){
            filter.put("roleName", sysRole.getRoleName());
        }
        page.setFilter(filter);

        page.setResult(replaceResourceId(sysRoleMapper.querySysRoleList(page)));
        page.setTotal(sysRoleMapper.querySysRoleCount(page.getFilter()));
        model.addAttribute("page",page);
        
        SysResource sysResource = new SysResource();
        sysResource.setParentId(0);
    	List<SysResource> resourceList = sysResourceMapper.findSysResourceByOne(sysResource);
    	if(!CheckUtil.isEmpty(resourceList)) {
            for(SysResource resource : resourceList) {
            	sysResource.setParentId(resource.getId().intValue());
                List<SysResource> childList = sysResourceMapper.findSysResourceByOne(sysResource);
                resource.setChildList(childList);
            }
        }
        model.addAttribute("NodeResources",resourceList);
        
        return "backstage/sysRoleList";
    }

    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public String addOrUpdateSysRole(Model model, SysRole sysRole, HttpServletRequest request) throws IOException{
        Long count = 0l;
        Boolean flag = false;
        //更新人和更新时间
        sysRole.setUpdateUser(getCurrentUser().getId().intValue());
        sysRole.setUpdateTime(new Date());
        if(CheckUtil.isEmpty(sysRole.getId())){

        	//创建 人和创建时间
        	sysRole.setCreateUser(getCurrentUser().getId().intValue());
        	sysRole.setCreateTime(new Date());

            count = sysRoleMapper.insertSysRole(sysRole);
            flag = changeSysResourceRole(sysRole.getResourceId(),sysRole.getId().intValue());
        } else{
        	count = sysRoleMapper.updateSysRole(sysRole);
        	flag = changeSysResourceRole(sysRole.getResourceId(),sysRole.getId().intValue());
        }

        this.sessionPutNodeResource(request);        //加载侧边条资源
        this.sessionPutResource(request);	//角色资源与全部资源放入session

        Map<String, Object> result = new HashMap<String, Object>();
        if(flag){
        	flag = count > 0 ? true : false;
        }
        result.put("suc", flag);
        return JSON.toJSONString(result);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String deleteSysRole(Model model,SysRole sysRole, Long id, HttpServletRequest request) throws IOException{
        boolean flag=false;

        sysRoleMapper.deleteById(id);
        
        this.sessionPutNodeResource(request);        //加载侧边条资源
        this.sessionPutResource(request);	//角色资源与全部资源放入session

        flag = true;
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("obj", flag);
        return JSON.toJSONString(result);
    }

    /**
     * 檢查角色名是否已存在
     * @param roleName
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/checkRoleName")
    @ResponseBody
    public String checkRoleName(String roleName,Long id) throws Exception
    {
        SysRole sysRole=new SysRole();
        if(roleName != null && !roleName.equals("")){
            sysRole.setRoleName(roleName);
        }
        if(id!= null && !id.equals("")){
            sysRole.setId(id);
        }
        
        Integer fg = 0;
        List<SysRole> roleList = sysRoleMapper.findSysRoleByOne(sysRole);
        if(roleList!=null && roleList.size()>0){
        	fg = 1;
        }
        return Boolean.toString(fg==0);
    }
    
	/**
	 * 角色关联资源
	 * @param resource
	 * @param roleId
	 * @return
	 */
	public Boolean changeSysResourceRole(String resource, Integer roleId){
		SysResourceRole sysResourceRole = new SysResourceRole();
		sysResourceRole.setRoleId(roleId);
		List<SysResourceRole> sysResourceRoleList = sysRoleMapper.findSysResourceRole(sysResourceRole);
		if(sysResourceRoleList != null && sysResourceRoleList.size()>0){
			for(SysResourceRole srr:sysResourceRoleList){
				sysRoleMapper.deleteSysResourceRoleById(srr.getId());
			}
		}
		if(resource!=null && !resource.equals("")){
			String[] resourceIds = resource.split(",");
			for(String resourceId:resourceIds){
				sysResourceRole = new SysResourceRole();
				sysResourceRole.setRoleId(roleId);
				sysResourceRole.setResourceId(Integer.parseInt(resourceId));
				sysRoleMapper.insertSysResourceRole(sysResourceRole);
			}
		}
		return true;
	}

	/**
	 * 根据角色查询对应的资源
	 * @param sysRoleList
	 * @return
	 */
	public List<SysRole> replaceResourceId(List<SysRole> sysRoleList){
		if(sysRoleList != null && sysRoleList.size()>0){
			for(SysRole sysRole:sysRoleList){
				SysResourceRole sysResourceRole = new SysResourceRole();
				sysResourceRole.setRoleId(sysRole.getId().intValue());
				List<SysResourceRole> sysResourceRoleList = sysRoleMapper.findSysResourceRole(sysResourceRole);
				String resourceId = "";
				if(sysResourceRoleList != null && sysResourceRoleList.size()>0){
					for(SysResourceRole srr:sysResourceRoleList){
						resourceId += srr.getResourceId() + ",";
					}
					resourceId = resourceId.substring(0, resourceId.length()-1);
				}
				sysRole.setResourceId(resourceId);
			}
		}
		return sysRoleList;
	}
}
